package com.start.shop.modules.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.start.shop.common.constant.RspCode;
import com.start.shop.common.exception.MyException;
import com.start.shop.modules.repository.dao.CouponConfigDao;
import com.start.shop.modules.repository.dao.CouponDao;
import com.start.shop.modules.repository.entity.CouponConfig;
import com.start.shop.modules.service.ICouponConfigService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CouponConfigServiceImpl implements ICouponConfigService{
		
	@Autowired
	CouponDao couponDao;

	@Autowired
	CouponConfigDao couponConfigDao;

	/**
	 * 查询所有优惠券配置
	 */
	@Override
	@Cacheable(cacheNames = "Shop::CouponConfig", key = "#sortId")
	public CouponConfig getCouponConifgById(int sortId) {
		return couponConfigDao.selectCouponConfigBySorId(sortId);
	}
	
	
	/**
	 * 关闭过期的优惠券
	 */
	@Override
	public int shutDownExpireCouponConfig() {
		
		return couponConfigDao.updateExpireCouponConfig();
	}
	
	/**
	 * 查询所有优惠券配置
	 */
	@Override
	public int updateCouponConfigById(CouponConfig couponConfig) {
		return couponConfigDao.update(couponConfig);
	}

	/**
	 * 扣减优惠券库存
	 */
	@Override
	public void couponStockOut(int sortId, int num) {
		if (couponConfigDao.updateStockOut(sortId, num)==0) {
			log.error("扣减库存失败，优惠券种类【{}】数量【{}】", sortId, num);
			throw new MyException(RspCode.COUPON_STOCK_NOT_ENOUGH);
		}
	}
	
}
